/**
 * Copyright (C), 2011-2016 
 * File Name: Contract.java
 * Encoding: UTF-8
 * Date: Oct 18, 2011
 * History: 
 */
package com.swak.frame.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* MD5摘要工具类
* @author Wayne Wan(bestirwiny@gmail.com)
* @version Revision: 1.00 Date: Oct 18, 2011
*/
public class MessageDigester {
	
	/**
	 * 取得一个MD5摘要计算实例
	 * @return
	 */
	private static MessageDigest getDigester(){
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md;
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 */
	public static int getMd5Int(String s)
	{
		String ss = Md5Digest(s);
		return Integer.parseInt(ss.substring(0,7), 16);
	}
	
	/**
	 * 对字符串s做摘要计算
	 * @param s
	 * @return
	 */
	public static String Md5Digest(String s)
	{
		MessageDigest md = getDigester();
		if(md==null) {
			return null;
		}
		md.update(s.getBytes());
		byte []  result = md.digest();
		return getMd5String(result);
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 */
	public static int getMd5Int(String s, String encode)
	{
		String ss = Md5Digest(s, encode);
		return Integer.parseInt(ss.substring(0,7), 16);
	}
	
	/**
	 * 对字符串s做摘要计算
	 * @param s
	 * @return
	 */
	public static String Md5Digest(String s, String encode)
	{
		MessageDigest md = getDigester();
		if(md==null) {
			return null;
		}
		byte [] result ;
		try {
			md.update(s.getBytes(encode));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		result = md.digest();
		
		return getMd5String(result);
	}
	
	/**
	 * 对流中的数据做摘要计算
	 * @param input
	 * @return
	 */
	public static String Md5Digest(InputStream input)
	{
		MessageDigest md = getDigester();
		if(md==null) {
			return null;
		}
		byte [] result = null;
		byte[] buf = new byte[1024*5];
		int readCount = 0;
		try
		{
			while((readCount = input.read(buf))>0)
			{
				md.update(buf, 0 , readCount);
			}
			result = md.digest();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return getMd5String(result);
	}
	
	/**
	 * 对字节数组做摘要
	 * @param result
	 * @return
	 */
	private static String getMd5String(byte[] result)
	{
		StringBuffer sb = new StringBuffer();
		for(byte b : result)
		{
			String temp = Integer.toHexString(b&0xff);
			sb.append(temp.length()<2?"0"+temp:temp);
		}
		return sb.toString();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try
		{
			System.out.println(Md5Digest("StringBuffer sb = new StringBuffer()dxmc_com.newheight.advertise.dolphin.service.impl.AdvertisementServiceImpl#getAdvertisement_1_0_1_SHANGJIA_1MALL_PEIXUN_FIRST_null_4_null_null_null_null_null_null_null_0"));
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

}
